<template>
  <div>
    <!-- 搜索表单
          el-row + el-col 可以实现栅格系统
            栅格系统可以动态的根据电脑分辨率计算，将每一行分成若干个固定的格子(24个)

            el-row代表一行 24个格子
            el-col代表 列 通过span指定这一列占多少个格子
    -->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字">
              <el-input
                style="width: 100%"
                v-model="searchObj.keyword"
                placeholder="用户名、姓名、手机号码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                :unlink-panels="true"
                type="daterange"
                range-separator="To"
                v-model="searchObj.times"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" size="small" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="small" @click="reset">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!--添加按钮-->
    <div class="tools-div">
      <el-button type="success" size="small" @click="dialogVisible = true">
        添 加
      </el-button>
      <el-button type="danger" size="small" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <!---数据表格-->
    <el-table
      :data="list"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column type="index" label="序号" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="phone" label="手机" />
      <el-table-column prop="avatar" label="头像" #default="scope">
        <img :src="scope.row.avatar" width="50" />
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="status" label="状态" #default="scope">
        {{ scope.row.status == 1 ? '正常' : '停用' }}
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="280" #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="handleShowUpdateDialog(scope.row)"
        >
          修改
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
          删除
        </el-button>
        <el-button
          type="warning"
          size="small"
          @click="handleShowAssignRolesDialog(scope.row)"
        >
          分配角色
        </el-button>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-sizes="[1, 2, 3, 4, 5]"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      layout="total, sizes, prev, pager, next"
      @size-change="fetchData"
      @current-change="fetchData"
      :total="total"
    />
    <!-- 新增或更新用户的对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
      <el-form label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="sysUser.username" />
        </el-form-item>
        <el-form-item label="密码" v-if="!sysUser.id">
          <el-input v-model="sysUser.password" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="sysUser.name" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="sysUser.phone" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadAvatarSuccess"
            :headers="headers"
            :data="{ module: 'avatar' }"
            :on-error="handleUploadAvatarError"
          >
            <!-- :data="{ module: 'avatar' }"表示 携带请求参数 url?module=avatar -->
            <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="sysUser.description" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdateOrSaveUser">
            提交
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="sysUser.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox
            v-model="userRoleIds"
            v-for="role in allRoles"
            :key="role.id"
            :checked="role.checked"
            :label="role.id"
          >
            {{ role.roleName }}
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleAssignRoles">提交</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApp } from '@/pinia/modules/app'
import {
  GetUserById,
  FindUserPage,
  DeleteUser,
  UpdateUser,
  SaveUser,
  BatchDeleteUser,
} from '@/api/sysUser'
import { FindAllRoleByUserId } from '@/api/sysRole'
import { AssignRoles2User } from '@/api/sysUserRole'
//========= 分配角色start==
let dialogRoleVisible = ref(false)
let userRoleIds = ref([]) //选中的要分配的角色的id集合
let allRoles = ref([]) //所有的角色列表
//对话框提交按钮事件函数
let handleAssignRoles = async () => {
  //获取选中的要分配的角色id列表
  // console.log(userRoleIds.value, sysUser.value.id)
  //提交分配角色的请求：  还需要userId
  await AssignRoles2User(sysUser.value.id, userRoleIds.value)
  ElMessage.success('角色分配成功')
  //关闭对话框
  dialogRoleVisible.value = false
}
// 分配角色按钮事件函数：弹出分配角色的对话框
let handleShowAssignRolesDialog = async row => {
  // console.log(userRoleIds.value)
  //清空两个数组的缓存 否则回显会失败......
  userRoleIds.value = []
  allRoles.value = []
  sysUser.value = row
  const { data } = await FindAllRoleByUserId(row.id)
  allRoles.value = data
  dialogRoleVisible.value = true
}
let handleCloseDialog = () => {
  // userRoleIds.value = []
  dialogRoleVisible.value = false
}
//========= 分配角色end==

let list = ref([])
let total = ref(0)
let pageNum = ref(1)
let pageSize = ref(3)
let searchObj = ref({
  keyword: '',
  createTimeStart: '',
  createTimeEnd: '',
})

//=== 批量删除事件函数
let handleBatchDelete = async () => {
  //1、获取选中的要删除的所有行的id集合
  //只需要获取最后一个选中行改变回调时传入的数组  并且取出所有的id即可
  console.log(checkedRows.value)
  let idsArr = []
  checkedRows.value.forEach(checked => {
    idsArr.push(checked.id)
  })

  console.log(idsArr)
  //2、提交id集合到后端批量删除
  await BatchDeleteUser(idsArr)
  ElMessage.success('批量删除成功')
  //刷新页面
  fetchData()
}
// 表格的选中行状态改变时的回调
let checkedRows = ref([])
let handleSelectionChange = selection => {
  // console.log(selection)
  checkedRows.value = selection
}

//=== 更新
//1、更新按钮事件函数：  查询要更新的用户信息回显
let handleShowUpdateDialog = async row => {
  //根据id查询要更新的用户
  const { data } = await GetUserById(row.id)
  sysUser.value = data
  //显示对话框
  dialogVisible.value = true
}
//2、对话框提交按钮事件函数
let handleUpdateOrSaveUser = () => {
  if (sysUser.value.id) {
    handleUpdate()
  } else {
    handleSaveUser()
  }
}
let handleUpdate = async () => {
  await UpdateUser(sysUser.value)
  ElMessage.success('更新成功')
  fetchData() //刷新页面数据
  dialogVisible.value = false //关闭对话框
  sysUser.value = {} //清空缓存数据
}

//=== 新增对话框提交按钮事件函数
let handleSaveUser = async () => {
  await SaveUser(sysUser.value)
  ElMessage.success('新增成功')
  fetchData() //刷新页面数据
  dialogVisible.value = false //关闭对话框
  sysUser.value = {} //清空缓存数据
}
//=== 上传组件的属性和函数
let headers = {
  token: useApp().authorization.token,
}
let uploadUrl = ref('http://localhost:8501/admin/system/file/upload') //上传接口访问时也需要在请求头中携带token
//头像上传连接服务器成功的回调
let handleUploadAvatarSuccess = response => {
  //上传组件提交请求时没有经过request.js中的响应拦截器处理
  // 当前方法回调时 不一定上传成功
  if (+response.code === 200) {
    ElMessage.success('上传成功')
    console.log(response.data)
    console.log(response.code)
    sysUser.value.avatar = response.data
  } else {
    ElMessage.error(response.message)
  }
}
//头像上传连接服务器失败时的回调
let handleUploadAvatarError = () => {
  ElMessage.error('服务器连接失败')
}
//====

let dialogVisible = ref(false)
let sysUser = ref({})
//===删除按钮事件函数
let handleDelete = async row => {
  await DeleteUser(row.id)
  //删除成功提示
  ElMessage.success('删除成功')
  //刷新页面
  fetchData()
}

//===搜索按钮事件函数
let handleSearch = () => {
  console.log(searchObj.value)
  //提交带条件的查询的请求
  //需要手动解析开始和截止日期时间 然后再提交请求查询数据
  if (searchObj.value.times) {
    searchObj.value.createTimeStart = searchObj.value.times[0]
    searchObj.value.createTimeEnd = searchObj.value.times[1]
    searchObj.value.times = ''
  }
  fetchData()
}
let reset = () => {
  pageNum.value = 1
  pageSize.value = 3
  searchObj.value = {}
  fetchData()
}

//查询分页数据渲染展示
onMounted(() => {
  fetchData()
})

//查询分页数据函数
let fetchData = async () => {
  const { code, message, data } = await FindUserPage(
    pageNum.value,
    pageSize.value,
    searchObj.value
  )
  if (+code === 200) {
    list.value = data.list
    total.value = data.total
  } else {
    ElMessage.error(message)
  }
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
